#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils.util import datetime_now_str
from controls.mongo import db_shitouren as db

# collection in mongodb
coll = db.city_card
"""db.city_card collection has
{
   "cityid" : 1,
   "ver" : 1,
   "cards" : [{
      "cardid" : 1,
      "type" : 1,
      "source": 1,
      "cardname" : "大虾烧白菜",
      "starlevel" : 5,
      "imgid" : "1000023",
      "imgurl" : "http://static.shitouren.com/group1/M00/00/00/xxxxxxxxxxxxxxxx.jpg",
      "desc" : "地道的胶东风味。荤素搭配，看上去无比诱人，白菜吸收了虾的汤汁，虾肉吃起来嫩滑爽口，白菜还有浓浓的海鲜味道哦。",
      "label" : ["静静的晒太阳","放松身体","安静的晒太阳","晒太阳","武大晒太阳"],
      "collectcount" : 15
   }
   ]
   utime:           更新时间(str)
}
"""


def get_city_card(cityid):
    '''get city's cards by cityid
    '''
    cond = {}
    if cityid:
        cond['cityid'] = int(cityid)
    else:
        return None
    res = coll.find_one(cond, {'_id': 0, 'cityid': 1, 'ver': 1, 'cards': 1})
    return res


def is_exist(cityid):
    cond = {}
    if cityid:
        cond['cityid'] = int(cityid)
    else:
        return False
    res = coll.find(cond, {'_id': 1}).count()
    return res > 0


def add_city_card(cityid, ver, cards_list):
    '''add card for a city
    '''
    res = coll.insert({'cityid': int(cityid), 'ver': ver, 'cards': cards_list, 'utime': datetime_now_str()})

    return res


def update_city_card(cityid, cards_list):
    '''update card for a city
    '''
    res = None
    if is_exist(cityid):
        oldcards = get_city_card(cityid)
        ver = 1
        if oldcards:
            ver += oldcards['ver']
        res = coll.update({'cityid': int(cityid)},
                          {'cityid': int(cityid), 'ver': ver, 'cards': cards_list, 'utime': datetime_now_str()})
    else:
        res = add_city_card(cityid, 1, cards_list)

    return res


def del_city_card(cityid):
    '''del city's all cards by cityid
    res:{u'syncMillis': 0, u'ok': 1.0, u'err': None, u'writtenTo': None, u'connectionId': 29, u'n': 1}
    '''
    res = coll.remove({'cityid': int(cityid)})
    return res


if __name__ == "__main__":
    print 'main start'
    print '=============insert test data'
    print update_city_card(999, [991, 992, 993])
    print add_city_card(998, 1, [981, 982, 983])

    print '============='
    print get_city_card(999)
    print update_city_card(999, [994, 995, 996])
    print get_city_card(999)

    print '============='
    print is_exist(999)
    print is_exist(998)
    print del_city_card(999)
    print del_city_card(998)
    print is_exist(999)
    print is_exist(998)
